#!/bin/sh
set -e

linux_version=`uname -r`
mod_dir="/lib/modules/${linux_version}"
service_file="/etc/systemd/system/shyper.service"

echo "Copy shyper.ko to ${mod_dir} ... \c"
cp shyper.ko ${mod_dir}
echo "ok"

echo "Add shyper to /etc/modules-load.d/modules.conf ... \c"
touch /etc/modules-load.d/modules.conf
if [ `grep -c shyper /etc/modules-load.d/modules.conf` -eq '0' ];then
    echo "shyper" >> /etc/modules-load.d/modules.conf
fi
echo "ok"

echo "Remove shyper mod ... \c"
if [ `lsmod | grep -c shyper` -ne '0' ];then
    if [ `ps -ef | grep -c /usr/bin/shyper` -ne '1' ];then
        systemctl stop shyper
    fi
    rmmod shyper.ko
fi
echo "ok"

echo "Install shyper mod ... \c"
depmod
modprobe shyper
echo "ok"

echo "Install cli to ${mod_dir} ... \c"
cp cli/shyper ${mod_dir}
chmod +x ${mod_dir}/shyper
ln -sf ${mod_dir}/shyper /usr/bin/shyper
echo "ok"

echo "Setup Shyper Service => ${service_file} ... \c"
echo "[Unit]" > ${service_file}
echo "Description=shyper server daemon" >> ${service_file}
echo "After=systemd-modules-load.service" >> ${service_file}

echo "[Service]" >> ${service_file}
echo "Type=simple" >> ${service_file}
echo "StandardOutput=journal" >> ${service_file}
echo "ExecStart=/usr/bin/shyper sys daemon" >> ${service_file}
echo "ExecReload=/usr/bin/shyper sys daemon" >> ${service_file}
echo "Restart=always" >> ${service_file}
echo "RestartSec=0" >> ${service_file}

echo "[Install]" >> ${service_file}
echo "WantedBy=multi-user.target" >> ${service_file}
echo "ok"

echo "Start Shyper Service ... \c"
systemctl enable shyper --now
echo "ok"


if [ `shyper vm getvmid` -eq '0' ];then
    if [ `cat /root/.bashrc | grep -c "alias reboot='shyper sys reboot'"` -eq '0' ];then
        echo "alias reboot => shyper sys reboot"
        echo "alias reboot='shyper sys reboot'" >> /root/.bashrc
    fi
    if [ `cat /root/.bashrc | grep -c "alias poweroff='shyper sys shutdown'"` -eq '0' ];then
        echo "alias shutdown => shyper sys shutdown"
        echo "alias poweroff='shyper sys shutdown'"  >> /root/.bashrc
    fi
    echo "Alias reboot & shutdown for Management VM"
fi